<!-- 自动回复管理 -->
<template>
  <div class="app-container">
    <el-row :gutter="24">
      <!-- 自动回复列表 -->
      <el-col :lg="24" :xs="24">
        <!-- 搜索区域 -->
        <div class="search-container">
          <el-form
            ref="queryFormRef"
            :model="queryParams"
            :inline="true"
            label-width="auto"
          >
            <el-form-item label="关键字" prop="keywords">
              <el-input
                v-model="queryParams.keywords"
                placeholder="自动回关键字"
                clearable
              />
            </el-form-item>
            <el-form-item class="search-buttons">
              <el-button type="primary" icon="search" @click="handleQuery">
                搜索
              </el-button>
              <el-button icon="refresh" @click="handleResetQuery">
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="hover" class="data-table">
          <div class="data-table__toolbar" style="margin-bottom: 10px">
            <div class="data-table__toolbar--actions">
              <el-button
                v-hasPerm="['autoReplyEdit']"
                type="success"
                icon="plus"
                @click="handleOpenDialog()"
              >
                新增
              </el-button>
              <el-button
                v-hasPerm="'autoReplyDelBtn'"
                type="danger"
                icon="delete"
                :disabled="selectIds.length === 0"
                @click="handleDelete()"
              >
                删除
              </el-button>
            </div>
          </div>

          <el-table
            v-loading="loading"
            :data="pageData"
            :selectable="selectable"
            border
            stripe
            highlight-current-row
            class="data-table__content"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="客服id" align="center" prop="admin_id" />
            <el-table-column
              label="客服名称"
              align="center"
              prop="admin_name"
            />
            <el-table-column label="回复类型" align="center">
              <!-- //消息类型 0欢迎语 1自动回复 2关键词回复 -->
              <template #default="scope">
                <el-tag type="primary" v-if="scope.row.msg_type === 0">
                  欢迎语
                </el-tag>
                <el-tag type="success" v-if="scope.row.msg_type === 1">
                  自动回复
                </el-tag>
                <el-tag type="warning" v-if="scope.row.msg_type === 2">
                  关键词回复
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="标题" align="center" prop="title" />
            <el-table-column label="消息内容" align="center">
              <template #default="scope">
                <div v-if="scope.row.type == 'text'">
                  <div v-html="scope.row.content"></div>
                </div>

                <div v-if="scope.row.type == 'image'">
                  <el-image
                    :preview-src-list="[scope.row.content]"
                    :src="scope.row.content"
                    style="width: 100px; height: 100px"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="消息类型" align="center">
              <template #default="scope">
                <el-tag type="success" v-if="scope.row.type === 'text'">
                  文本消息
                </el-tag>
                <el-tag type="warning" v-if="scope.row.type === 'image'">
                  图片消息
                </el-tag>
                <el-tag type="info" v-if="scope.row.type === 'video'">
                  视频消息
                </el-tag>
                <el-tag type="danger" v-if="scope.row.type === 'audio'">
                  音频消息
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.status === 1">正常</el-tag>
                <el-tag v-else type="info">禁用</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="排序" align="center" prop="sort" />
            <el-table-column
              label="创建时间"
              align="center"
              prop="created_at"
              width="200"
            />
            <el-table-column
              label="更新时间"
              align="center"
              prop="updated_at"
              width="200"
            />
            <el-table-column label="操作" fixed="right" align="center">
              <template #default="scope">
                <el-button
                  v-hasPerm="'autoReplyEdit'"
                  type="primary"
                  icon="edit"
                  link
                  size="small"
                  @click="handleOpenDialog(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  v-hasPerm="'autoReplyDelBtn'"
                  type="danger"
                  icon="delete"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            v-model:current-page="queryParams.page"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[15, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleQuery"
            @current-change="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="1000"
      :before-close="handleCloseDialog"
      :align-center="true"
      :close-on-click-modal="false"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="客服id" prop="admin_id">
          <el-select v-model="formData.admin_id" placeholder="请选择">
            <el-option
              v-for="item in adminOptions"
              :key="item.id"
              :label="item.username"
              :value="item.id ?? ''"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="消息类型" prop="msg_type">
          <!-- //回复类型 0欢迎语 1自动回复 2关键词回复 -->
          <el-radio-group v-model="formData.msg_type">
            <el-radio :label="0">欢迎语</el-radio>
            <el-radio :label="1">自动回复</el-radio>
            <el-radio :label="2">关键词回复</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="消息类型" prop="type">
          <!-- text 文本消息,  image 图片消息, video 视频消息, audio 音频消息 -->
          <el-radio-group v-model="formData.type">
            <el-radio :label="'text'">文本消息</el-radio>
            <el-radio :label="'image'">图片消息</el-radio>
            <!-- <el-radio :label="'video'">视频消息</el-radio> -->
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item
          label="消息内容"
          prop="content"
          v-if="formData.type === 'text'"
        >
          <WangEditor v-model="formData.content" height="400px" />
        </el-form-item>
        <el-form-item
          label="消息内容"
          prop="content"
          v-if="formData.type === 'image'"
        >
          <SingleImageUpload v-model="formData.content" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" placeholder="" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useAppStore } from "@/store/modules/app";
import { DeviceEnum } from "@/enums/DeviceEnum";
import WangEditor from "@/components/WangEditor/index.vue";

import ReplyAPI, {
  ReplyInfo,
  ReplyInfoListVO,
  ReplyPageQuery,
  ReplyInfoList,
} from "@/api/system/reply.api";
import UserAPI, { UserListVO, UserList } from "@/api/system/user.api";
defineOptions({
  name: "AutoReply",
  inheritAttrs: false,
});

const appStore = useAppStore();
// 角色下拉数据源
const adminOptions = ref<UserList[]>();
const queryFormRef = ref();
const dataFormRef = ref();

const queryParams = reactive<ReplyPageQuery>({
  page: 1,
  pageSize: 15,
});
const selectable = (row: ReplyInfo) => ![1].includes(Number(row.id));
const pageData = ref<ReplyInfoList[]>();
const total = ref(0);
const loading = ref(false);

const dialog = reactive({
  visible: false,
  title: "新增自动回复",
});
const drawerSize = computed(() =>
  appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"
);

let formData = reactive<ReplyInfo>({
  id: "",
  /** 客服id */
  admin_id: 0,
  /** 回复类型 0欢迎语 1自动回复 2关键词回复 */
  msg_type: 0,
  // 标题
  title: "",
  /** 消息内容 */
  content: "",
  //消息类型 text 文本消息,  image 图片消息, video 视频消息, audio 音频消息
  type: "text",
  /** 状态 */
  status: 1,
  //排序
  sort: 0,
  //创建时间
  created_at: "",
});

const rules = reactive({
  admin_id: [{ required: true, message: "客服id不能为空", trigger: "blur" }],
  content: [{ required: true, message: "消息内容不能为空", trigger: "blur" }],
});

// 初始化查询参数
async function initParams() {
  UserAPI.getPage({ page: 1, pageSize: 1000 })
    .then((data: UserListVO) => {
      adminOptions.value = data.list;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 选中的自动回复ID
const selectIds = ref<number[]>([]);

// 查询
async function handleQuery() {
  loading.value = true;
  ReplyAPI.getPage(queryParams)
    .then((data: ReplyInfoListVO) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.page = 1;
  queryParams.keywords = "";
  handleQuery();
}

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

/**
 * 打开弹窗
 *
 * @param id 自动回复ID
 */
async function handleOpenDialog(user?: ReplyInfo) {
  dialog.visible = true;
  if (user?.id) {
    dialog.title = "修改自动回复";
    //复制 user 给formData.value
    Object.assign(formData, user);
  } else {
    dialog.title = "新增自动回复";
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = "";
  formData.admin_id = 0;
  formData.msg_type = 0;
  formData.title = "";
  formData.type = "text";
  formData.content = "";
  formData.status = 1;
  formData.sort = 0;
}

// 提交自动回复表单（防抖）
const handleSubmit = useDebounceFn(() => {
  dataFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      if (userId) {
        ReplyAPI.update(formData)
          .then(() => {
            ElMessage.success("修改自动回复成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        ReplyAPI.create(formData)
          .then(() => {
            ElMessage.success("新增自动回复成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);

/**
 * 删除自动回复
 *
 * @param id  自动回复ID
 */
function handleDelete(id?: number) {
  const userIds = [id || selectIds.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除自动回复?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      console.log(userIds);
      ReplyAPI.deleteByIds({ ids: userIds })
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  initParams();
  handleQuery();
});
</script>
